import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
Vue.use(Router)

/* Layout */
import Layout from '@/layout'
// 导入动态路由表
import { asyncRoutes } from './dynamicRoute'

export const staticRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' }
    }]
  },
  {
    path: '/roleAdd',
    component: () => import('@/views/System/Role/AddRole')
  },
  {
    path: '/roleEdit',
    component: () => import('@/views/System/Role/EditRole')
  },
  {
    path: '/exterpriseDetail',
    component: () => import('@/views/Park/Enterprise/Detail')
  },
  {
    path: '/big-screen',
    hidden: true
  }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes
})
const router = createRouter()

//重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
  console.log('重置路由',router.matcher)
}

//处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
      return item.split(':')[0]
  })
  // 去重
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  // 去重
  return [...new Set(newArr)]
}
// 根据权限标识过滤路由表
function filterRoute(firstRoutePerms, secondRoutePerms) {
  // 过滤一级路由
  const newRoutes = asyncRoutes.filter(item => {
    return firstRoutePerms.includes(item.permission)
  })
  // 过滤二级路由
  return newRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(child => secondRoutePerms.includes(child.permission))
    }
  })
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 登录页面直接放行
  if (to.path === '/login') {
    next()
  } else {
    const token = store.state.user.token
    // 判断是否有token
    if (token) {
      // 放行
      next()

      if (!store.state.user.profile.id) {
        //获取用户权限列表数据
        const permissions = await store.dispatch('user/getProfile')
        console.log('权限列表', permissions)
        // 处理一级与二级路由权限数据
        const firstRoutePerms = getFirstRoutePerms(permissions)
        console.log('一级权限',firstRoutePerms)
        const secondRoutePerms = getSecondRoutePerms(permissions)
        console.log('二级权限',secondRoutePerms)

        // 根据权限标识过滤路由表
        const filterRoutes = filterRoute(firstRoutePerms, secondRoutePerms)
        console.log('过滤后的路由',filterRoutes)
        //addRoute动态添加路由
        // '*:*:*' 表示管理员，拥有所有的权限
        if (permissions.includes('*:*:*')) {
          // 添加路由
          asyncRoutes.forEach(item => router.addRoute(item))
          store.commit('menu/setMenuList', asyncRoutes)
        } else {
          // 添加路由
          filterRoutes.forEach(item => router.addRoute(item))
          store.commit('menu/setMenuList', filterRoutes)
        }

        // 添加404路由
        router.addRoute({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
      }

    } else {
      // 跳转回登录页
      next('/login')
    }
  }
})

export default router
